package com.wmlt.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wmlt.entity.LiveBroadcast;
import com.wmlt.entity.LiveBroadcastResponseData;
import com.wmlt.service.LiveBroadcastService;
import com.wmlt.service.impl.LiveBroadcastServiceImpl;
import com.wmlt.util.GetRequestJsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 直播API
 * create by huangziqideveloper@gmail.com
 */

@WebServlet("/live")
public class LiveBroadcastApi extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        resp.setContentType("text/json;charset=utf-8");
        switch (path) {
            case "/live/on_connect":
                onConnect(req, resp);
                break;
            case "/live/on_play":
                onPlay(req, resp);
                break;
            case "/live/on_publish":
                onPublish(req, resp);
                break;
            case "/live/on_done":
                onPlayDone(req, resp);
                break;
            case "/live/on_publish_done":
                onPublishDone(req, resp);
                break;
            case "/live/on_record_done":
                onRecordDone(req, resp);
                break;
            case "/live/on_update":
                onUpdate(req, resp);
                break;
            case "/live/getLiveBroadcastList":
                getLiveBroadcastList(req, resp);
                break;
            case "/live/auditLiveBroadcast":
                auditLiveBroadcast(req, resp);
                break;
            case "/live/getUserInfoByLiveKey":
                getUserInfoByLiveKey(req, resp);
                break;
            case "/live/applyforLive":
                applyforLive(req, resp);
                break;
            case "/live/handlingLivestreamingRequests":
                handlingLivestreamingRequests(req, resp);
                break;
            case "/live/getLiveBroadcastInfoByUserId":
                getLiveBroadcastInfoByUserId(req, resp);
                break;
            case "/live/launchLiveBroadcast":
                launchLiveBroadcast(req, resp);
                break;
            default:
                resp.setStatus(404);
                break;
        }
    }

    /**
     * 用户连接响应
     *
     * @param request
     * @param response
     */
    private void onConnect(HttpServletRequest request, HttpServletResponse response) {
        debug(request, "on_connect");
    }

    /**
     * 用户观看直播响应
     *
     * @param request
     * @param response
     */
    private void onPlay(HttpServletRequest request, HttpServletResponse response) {
        debug(request, "on_play");
    }

    /**
     * 用户发起推流响应（主播开始推流）
     *
     * @param request
     * @param response
     */
    private void onPublish(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("用户发起直播开始推流");
        //获取用户的key
        //校验数据库中是否有这个key
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        LiveBroadcast liveBroadcast = liveBroadcastService.getLiveBroadcastByKey(request.getParameter("name"));
        if (liveBroadcast == null) {
            System.out.println("没有直播权限，滚蛋");
            response.sendError(401);
            return;
        } else {
            System.out.println("推流");
            liveBroadcastService.updateLiveState(request.getParameter("name"), 2);
            response.setStatus(200);
        }
        debug(request, "on_publish");
    }

    /**
     * 用户观看结束响应
     *
     * @param request
     * @param response
     */
    private void onPlayDone(HttpServletRequest request, HttpServletResponse response) {
        debug(request, "on_play_done");
    }

    /**
     * 主播推流结束响应
     *
     * @param request
     * @param response
     */
    private void onPublishDone(HttpServletRequest request, HttpServletResponse response) {
        //用户结束推流，删除直播表中的数据
        System.out.println("用户关闭直播结束推流");
        //获取用户的key
        //根据key修改数据中的数据
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();

        int result = liveBroadcastService.updateLiveState(request.getParameter("name"), 3);
        if (result > 0) {
            System.out.println("结束成功");
        } else {
            System.out.println("结束失败");
        }

        debug(request, "on_publish_done");
    }

    private void onRecordDone(HttpServletRequest request, HttpServletResponse response) {
        debug(request, "on_record_done");
    }


    private void onUpdate(HttpServletRequest request, HttpServletResponse response) {
        debug(request, "on_update");
    }

    private void getLiveBroadcastList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("获取直播列表");
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        List<LiveBroadcast> liveBroadcastList = liveBroadcastService.getLiveBroadcastList();
        String liveBroadcastListJsonStr = JSON.toJSONString(liveBroadcastList);
        response.getWriter().println(liveBroadcastListJsonStr);
    }

    /**
     * @description: 审核直播
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/8 9:06 上午
     */
    private void auditLiveBroadcast(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("获取直播间id");
        String[] liveBroadcastIdArr = request.getParameterValues("liveNo[]");
        int[] liveBroadcastIdArrInt = Arrays.stream(liveBroadcastIdArr).mapToInt(Integer::parseInt).toArray();
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        int result = liveBroadcastService.auditLiveBroadcast(liveBroadcastIdArrInt);
        LiveBroadcastResponseData data = new LiveBroadcastResponseData();
        data.setCode(result > 0 ? 200 : 400);
        data.setSuccess(result > 0 ? "成功" : "失败");
        String dataJsonStr = JSON.toJSONString(data);
        response.getWriter().println(dataJsonStr);
    }


    private String debug(HttpServletRequest request, String action) {
        String str = action + ": " + request.getRequestURI() + " " + request.getQueryString();
        System.out.println(str);
        return str;
    }

    private void getUserInfoByLiveKey(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("获取直播列表");
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        List<LiveBroadcast> liveBroadcastList = liveBroadcastService.getUserInfoByLiveKey(request.getParameter("stream"));
        String liveBroadcastListJsonStr = JSON.toJSONString(liveBroadcastList);
        response.getWriter().println(liveBroadcastListJsonStr);
    }

    /**
     * 用户申请直播
     *
     * @param request
     * @param response
     */
    private void applyforLive(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LiveBroadcast liveBroadcast = new LiveBroadcast();
        liveBroadcast.setStatus(1);
        liveBroadcast.setUserId(request.getParameter("userId"));
        int liveNo= (int) ((Math.random()*10)+1);
        liveBroadcast.setLiveNo(liveNo);
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        int result = liveBroadcastService.applyforLive(liveBroadcast);
        LiveBroadcastResponseData liveBroadcastResponseData = new LiveBroadcastResponseData();
        liveBroadcastResponseData.setCode(result > 0 ? 200 : 400);
        liveBroadcastResponseData.setSuccess(result > 0 ? "申请成功,等待管理员审核" : "申请失败");
        String jsonString = JSONObject.toJSONString(liveBroadcastResponseData);
        response.getWriter().println(jsonString);
    }

    private void getLiveBroadcastInfoByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LiveBroadcastService liveBroadcastService=new LiveBroadcastServiceImpl();
        LiveBroadcast liveBroadcast = liveBroadcastService.getLiveBroadcastInfoByUserId(request.getParameter("userId"));
        LiveBroadcastResponseData liveBroadcastResponseData = new LiveBroadcastResponseData();
        if (liveBroadcast==null){
            //没有申请过直播
            liveBroadcastResponseData.setCode(-1);
            liveBroadcastResponseData.setSuccess("可以申请直播");
        }else{
            if (liveBroadcast.getStatus()==0){
                //已经申请过直播了,等待审核
                liveBroadcastResponseData.setCode(0);
                liveBroadcastResponseData.setSuccess("已申请直播权限，等待管理员审核");
            }else if(liveBroadcast.getStatus()==1){
                //已经申请过直播了,并且已经审核通过
                liveBroadcastResponseData.setCode(1);
                liveBroadcastResponseData.setSuccess("恭喜您获得直播权限，现在可以去开播了");
            }else if(liveBroadcast.getStatus()==2){
                //正在开播
                liveBroadcastResponseData.setCode(2);
                liveBroadcastResponseData.setSuccess("正在开播");
            }else if(liveBroadcast.getStatus()==3){
                //直播结束
                liveBroadcastResponseData.setCode(3);
                liveBroadcastResponseData.setSuccess("直播结束");
            }else if(liveBroadcast.getStatus()==200){
                //等待上播
                liveBroadcastResponseData.setCode(200);
                liveBroadcastResponseData.setSuccess("直播准备就绪，等待推流！");
            }
        }

        String jsonString = JSONObject.toJSONString(liveBroadcastResponseData);
        response.getWriter().println(jsonString);

    }
    /**
     * @description: 发起直播，修改数据库直播表的信息
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/9 10:23 上午
     */
    private void launchLiveBroadcast(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(response, request);

        //获取标题对应的值
        String title = jsonObject.getString("title");
        System.out.println("title：" + title);

        //获取直播封面对应的值
        String liveImageUrl = jsonObject.getString("liveImageUrl");
        System.out.println("liveImageUrl：" + liveImageUrl);

        //获取作者对应的值
        String userId = jsonObject.getString("userId");
        System.out.println("userId：" + userId);



        LiveBroadcast liveBroadcast = new LiveBroadcast();
        liveBroadcast.setTitle(title);
        liveBroadcast.setLiveImageUrl(liveImageUrl);
        liveBroadcast.setUserId(userId);
        liveBroadcast.setStatus(200);//等待状态，当用户推流才是真正的开播

        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        System.out.println(liveBroadcast);
        int result = liveBroadcastService.launchLiveBroadcast(liveBroadcast);

        LiveBroadcastResponseData liveBroadcastResponseData = new LiveBroadcastResponseData();

        liveBroadcastResponseData.setCode(200);
        liveBroadcastResponseData.setSuccess("发起直播成功，赶快去推流叭！");
        String jsonString = JSONObject.toJSONString(liveBroadcastResponseData);
        response.getWriter().println(jsonString);

    }


    /**
     * 处理用户申请直播
     *
     * @param request
     * @param response
     */
    private void handlingLivestreamingRequests(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LiveBroadcastService liveBroadcastService = new LiveBroadcastServiceImpl();
        int result = liveBroadcastService.handlingLivestreamingRequests("b97cc37c034f40d8999c38434c9a5b1f");
        System.out.println(request.getParameter("userid"));
        response.getWriter().println(result);
    }
}
